import Vue from 'vue'
import store from '@/store/index'
import VueRouter from 'vue-router'
import Nprogress from 'nprogress' //实现效果
import { getToken } from '@/utils/auth'
import { getInfo } from '@/api/user'
import 'nprogress/nprogress.css' //对应的样式

import layout from '@/layout/index.vue'

Vue.use(VueRouter)

const errorPage = {
  path: '/error',
  name: '错误页面',
  redirect: '/error/403',
  component: layout,
}

const userPage = {
  path: '/user',
  name: '用户管理',
  redirect: '/user/userlist',
  component: layout,
}

const grantPage = {
  path: '/grant',
  name: '权限管理',
  redirect: '/grant/rolelist',
  component: layout,
}

const goodsPage = {
  path: '/goods',
  name: '商品管理',
  redirect: '/goods/goodslist',
  component: layout,
}

const storePage = {
  path: '/store',
  name: '店铺管理',
  redirect: '/store/storegoods',
  component: layout,
}

const brandPage = {
  path: '/brand',
  name: '品牌管理',
  redirect: '/brand/brandlist',
  component: layout,
}

const bannerPage = {
  path: '/banner',
  name: '轮播图管理',
  redirect: '/banner/bannerlist',
  component: layout,
}

const orderPage = {
  path: '/order',
  name: '订单管理',
  redirect: '/order/storeorder',
  component: layout,
}

const commentPage = {
  path: '/comment',
  name: '评论管理',
  redirect: '/comment/commentlist',
  component: layout,
}

const dashboardPage = {
  path: '/dashboard',
  name: '数据统计',
  icon: 'el-icon-data-analysis',
  component: () => import('@/views/dashboard'),
}

const chatPage = {
  path: '/chat',
  name: '消息中心',
  icon: 'el-icon-chat-dot-round',
  component: () => import('@/views/chat'),
}

const notFound = {
  path: '*',
  redirect: '/404',
  hidden: true,
}

export const routerMapping = {
  error: errorPage,
  user: userPage,
  grant: grantPage,
  goods: goodsPage,
  store: storePage,
  brand: brandPage,
  banner: bannerPage,
  order: orderPage,
  comment: commentPage,
  dashboard: dashboardPage,
  chat: chatPage,
}

const userlist = {
  path: 'userlist',

}

const constantRoutes = [
  {
    path: '/login',
    component: () => import('@/views/login/index'),
    hidden: true,
  },
  {
    path: '/',
    redirect: '/dashboard',
    component: () => import('@/layout'),
    children: [],
  },
  {
    path: '/403',
    component: () => import('@/views/error/403.vue'),
    hidden: true,
  },
  {
    path: '/404',
    component: () => import('@/views/error/404.vue'),
    hidden: true,
  },
]

const routes = [
  {
    path: '/redirect',
    component: () => import('@/layout/index'),
    hidden: true,
    children: [
      {
        path: '/redirect/:path(.*)',
        component: () => import('@/views/redirect'),
      },
    ],
  },
  {
    path: '/login',
    name: '登录',
    component: () => import('@/views/login/index'),
    hidden: true,
  },
  {
    path: '/',
    redirect: '/dashboard',
    component: () => import('@/layout'),
    children: [dashboardPage, chatPage],
  },
  {
    path: '/error',
    name: '错误页面',
    redirect: '/error/403',
    component: () => import('@/layout'),
    children: [
      {
        path: '403',
        name: '403',
        component: () => import('@/views/error/403.vue'),
      },
      {
        path: '404',
        name: '404',
        component: () => import('@/views/error/404.vue'),
      },
    ],
  },
  {
    path: '/403',
    component: () => import('@/views/error/403.vue'),
    hidden: true,
  },
  {
    path: '/404',
    component: () => import('@/views/error/404.vue'),
    hidden: true,
  },
  {
    path: '*',
    redirect: '/404',
    hidden: true,
  },
]

const router = new VueRouter({
  // routes,
  mode: 'history',
  base: process.env.NODE_ENV === 'production' ? '/preferred/index/' : '/index/',
  routes: constantRoutes,
})

Nprogress.configure({
  easing: 'ease', // 动画方式
  speed: 600, // 递增进度条的速度
  showSpinner: false, // 是否显示加载ico
  trickleSpeed: 200, // 自动递增间隔
  minimum: 0.3, // 初始化时的最小百分比
})


router.beforeEach((to, from, next) => {
  Nprogress.start()
  // console.log(to.path);
  if(to.path === '/login' || to.path === '/403' || to.path === '/404') {
    next()
  }else {
    const token = getToken()
    if(!token) {
      next('/login')
      Nprogress.done()
    }
    else {
      getInfo(token).then(res => {
        store.dispatch('user/setUserInfo', res.data)
      })
      next()
      Nprogress.done()
    }
  }
})

router.afterEach(() => {
  Nprogress.done()
})

export function initDynamicRoutes() {
  const currentRoutes = router.options.routes
  const routes = store._modules.root._children['permission'].state.routes
  // console.log(routes);
  routes.forEach((route) => {
    const target = routerMapping[route.matched]
    if(currentRoutes.indexOf(target) !== -1) {
      return
    }
    if (target && target.redirect) {
      if(route.children) {
        createRouterChildren(target, route)
      }
      target.icon = route.icon
      currentRoutes.push(target)
    } else {
      if(currentRoutes[1].children.indexOf(target) !== -1) {
        return
      }
      target.meta = route.permission ? route.permission : []
      currentRoutes[1].children.push(target)
    }
  })
  // console.log('动态生成', currentRoutes);
  currentRoutes.push(notFound)
  router.addRoutes(currentRoutes)
}

export function createRouterChildren(target, parent) {
  target.children = []
  parent.children.map(child => {
    let url = `${parent.matched}/${child.path}.vue`
    child.component = loadView(url)
    child.path = `${child.path}`
    child.meta = child.permission ? child.permission : []
    target.children.push(child)
  })
}

export const loadView = (view) => {
  return (resolve) => require([`@/views/${view}`], resolve)
}

export default router
